import socket
import json
import subprocess
from os.path import dirname, abspath


# 获取本地ip
def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
        return ip
    except Exception:
        print("未联网或ip获取失败，ip将被置为空字符串")
        return ''
    finally:
        s.close()


# 尝试转成json，如果出错，则给一个自定义的默认值
def try_transto_json(json_str, default_value):
    try:
        result = json.loads(json_str)
    except Exception as e:
        print(e)
        result = default_value
    return result


# 捕获系统异常
def system_exe_output(cmd):
    assert(type(cmd) == str)
    status, result = subprocess.getstatusoutput(cmd)
    if int(status) != 0:
        raise Exception(result)
    return result


# 把本地文件推送到远端服务器（需要ssh）
def push_file(src_path, dest_user, dest_host, dest_path=None, is_cover=True):
    cmd_conf = '-avzp'
    if not is_cover:
        cmd_conf += 'u'
    if dest_path is None:
        root_path = dirname(dirname(dirname(dirname(abspath(__file__)))))
        # dest_root_path = '/cloud/data/lirui/projects'
        dest_root_path = '/data/bigdata'
        dest_path = dirname(dest_root_path + src_path.replace(root_path, ''))
    print("推送到的目录是：%s" % dest_path)
    result = system_exe_output("rsync %s --progress %s %s@%s:%s" % (cmd_conf, src_path, dest_user, dest_host, dest_path))
    print(result)
    return result


# 把文件从远端服务器复制到本地（需要ssh）
def pull_file(src_user, src_host, src_path, dest_path, is_cover=True):
    cmd_conf = '-avz'
    if not is_cover:
        cmd_conf += 'u'
    result = system_exe_output("rsync %s %s@%s:%s %s " % (cmd_conf, src_user, src_host, src_path, dest_path))
    return result


if __name__ == '__main__':
    push_file('/Users/ruili/svn/data_scripts', 'www', '118.89.168.55', '/data/bigdata/')
